package com.example.demo.CookieText;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.HTTPTest.util.OKHttpUtil;
import okhttp3.*;

import javax.servlet.http.Cookie;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class saveCookieText {

    private static String cookieText = "JSESSIONID=";

    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(30, TimeUnit.SECONDS).readTimeout(30, TimeUnit.SECONDS).build();


    public static void main(String[] args) throws IOException {
//        String loginUrl = "http://114.116.17.1:8090/green-agri-price-api/login?username=super_admin&password=33Iot2013%21";
//
//        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), new JSONObject().toString());
//        Request request = new Request.Builder()
//                .url(loginUrl)
//                .post(requestBody)
//                .build();
//        Response response = client.newCall(request).execute();
//        if (response.code() == 200) {
//            String sessionId = extractSessionId(response.header("Set-Cookie"));
//            System.out.println(sessionId);
//        }else {
//            System.out.println("登录失败!");
//        }

// --------------

        String url = "http://114.116.17.1:8090/green-agri-price-api/api/price/stats";

        Map<String, Object> headersMap = new HashMap<>();
        String sessionId = "3A230820CE36F668E1F9F6D1FD0A4AED";
        headersMap.put("Cookie", cookieText + sessionId);
        Map<String, Object> doget = OKHttpUtil.doget(url +
                "?typeId=2" +
                "&province=%E6%B1%9F%E8%8B%8F%E7%9C%81" +
                "&city=" +
                "&county=" +
                "&startDate=2024-06-06" +
                "&endDate=2024-06-07", headersMap);
        System.out.println(doget);
    }

    // 从 Set-Cookie 头中提取 JSESSIONID
    private static String extractSessionId(String cookieHeader) {
        if (cookieHeader != null) {
            String[] cookies = cookieHeader.split(";");
            for (String cookie : cookies) {
                if (cookie.startsWith("JSESSIONID")) {
                    return cookie.split("=")[1];
                }
            }
        }
        return null;
    }
}
